package com.example.demo.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.List;

public class MomentsCommentGenerator {
    // 静态变量存储头像文件列表
    private static final List<File> avatarFiles = new ArrayList<>();
    private static final Random random = new Random();
    // 静态变量存储内容图片文件列表
    private static final List<File> contentImageFiles = new ArrayList<>();
    private static BufferedImage likeImage;
    private static BufferedImage noLikeImage;
    /**
     * 将 JAR 包内 static 目录下的资源转换为 File 对象
     * @param resourcePath 资源在 static 目录下的相对路径
     * @return File 对象，如果转换失败则返回 null
     */
    public static File getResourceAsFile(String resourcePath) {
        try (InputStream inputStream = MomentsCommentGenerator.class.getClassLoader().getResourceAsStream("static/" + resourcePath)) {
            if (inputStream == null) {
                return null;
            }
            // 创建临时文件
            File tempFile = File.createTempFile(String.valueOf(inputStream.hashCode()), ".tmp");
            tempFile.deleteOnExit();

            // 将输入流中的数据复制到临时文件
            try (OutputStream out = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }
            return tempFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    static {
        // 初始化时加载头像文件

        String basePath = System.getProperty("user.dir");
        System.out.println("初始化加载头像文件目录"+basePath);
        File avatarDir = new File(basePath + "/static/avatar");
        if (avatarDir.exists() && avatarDir.isDirectory()) {
            File[] files = avatarDir.listFiles((dir, name) ->
                    name.endsWith(".png") || name.endsWith(".jpg") || name.endsWith(".jfif"));
            if (files != null) {
                Collections.addAll(avatarFiles, files);
            }
        }
        System.out.println("加载的头像文件数量: " + avatarFiles.size());

        // 初始化时加载内容图片文件
        File contentImageDir = new File(basePath + "/static/content");
        if (contentImageDir.exists() && contentImageDir.isDirectory()) {
            File[] contentFiles = contentImageDir.listFiles((dir, name) ->
                    name.endsWith(".png") || name.endsWith(".jpg") || name.endsWith(".jfif"));
            if (contentFiles != null) {
                Collections.addAll(contentImageFiles, contentFiles);
            }
        }
        System.out.println("加载的内容图片文件数量: " + contentImageFiles.size());

        // 加载 like.png 和 no_like.png 图片并缩放
        try {
            BufferedImage originalLikeImage = ImageIO.read(new File(basePath + "/static/like.png"));
            BufferedImage originalNoLikeImage = ImageIO.read(new File(basePath + "/static/no_like.png"));

            // 缩放图片到 30x30
            likeImage = new BufferedImage(180, 180, BufferedImage.TYPE_INT_ARGB);
            noLikeImage = new BufferedImage(180, 180, BufferedImage.TYPE_INT_ARGB);

            Graphics2D likeG2d = likeImage.createGraphics();
            likeG2d.drawImage(originalLikeImage.getScaledInstance(60, 60, Image.SCALE_SMOOTH), 0, 0, null);
            likeG2d.dispose();

            Graphics2D noLikeG2d = noLikeImage.createGraphics();
            noLikeG2d.drawImage(originalNoLikeImage.getScaledInstance(60, 60, Image.SCALE_SMOOTH), 0, 0, null);
            noLikeG2d.dispose();

        } catch (IOException e) {
            System.err.println("加载 like 或 no_like 图片失败: " + e.getMessage());
        }
    }

    public static void main(String[] args) throws IOException {

    }


    public  static String getLikeImage(Content content,File fileImage) throws IOException {
        // 增大图片尺寸以提高分辨率
        int width = 1080;
        int height = 1920;
        Comment comment = new Comment();
        comment.setContent(content.getComment());
        comment.setTime(content.getCommentTime());
        comment.setLike(content.getCommentLike());
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置高质量渲染提示
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);


        // 用户信息（移除 avatarId 参数）
        drawUserInfo(g2d, 40, 40,
                RedBookStyleNicknameGenerator.generateRedBookNickname());

        // 正文内容（调整坐标和最大宽度）
        // 正文内容（调整坐标和最大宽度，传递时间和地点参数）
       int y = drawContent(g2d, 40, 90, width - 120,
                content.getContent(), content.getTime(),
                RandomProvinceGenerator.getRandomProvince()
                ,content.getLikes(),fileImage);

        // 评论列表
        List<Comment> comments = new ArrayList<>();
        comments.add(comment);

        // 绘制评论（调整坐标）
        drawComments(g2d, 40, y+20, width, height, comments);

        // 点赞数（调整坐标）
//        drawLikes(g2d, 60, 1200, width, "128 人点赞");

        g2d.dispose();
        String name =UUID.randomUUID()+".png";
        File path = new File("D:/landingsheng/result");
        if (!path.exists()) {
            path.mkdirs();
        }
        ImageIO.write(image, "png", new File("D:/landingsheng/result/"+name));
        System.out.println("图片生成成功！");
        return "http://192.168.31.241:8082/result/"+name;
    }


    private static void drawUserInfo(Graphics2D g2d, int x, int y,
                                     String username) {
        // 修改为使用随机头像文件
        drawAvatar(g2d, x, y,120);
        // 设置昵称颜色为 #808080
        g2d.setColor(new Color(0x808080));
        // 字体替换为黑体
        g2d.setFont(new Font("黑体", Font.PLAIN, 40));
        g2d.drawString(username, x + 140, y + 35);
    }
    private static int drawContent(Graphics2D g2d, int x, int y,
                                    int maxWidth, String text,
                                    String time, String location,
                                    int count,File imageUrl) {
        g2d.setColor(Color.decode("#333333"));
        // 字体替换为黑体
        g2d.setFont(new Font("黑体", Font.PLAIN, 45));

        List<String> lines = wrapContentText(g2d, text, maxWidth);
        int lineHeight = g2d.getFontMetrics().getHeight();
        for (int i = 0; i < lines.size(); i++) {
            g2d.drawString(lines.get(i), x + 140, y + (i + 1) * lineHeight);
        }

        // 计算内容绘制后的 y 坐标
        int contentEndY = y + lines.size() * lineHeight + 20; // 20 为内容和图片之间的间距

        // 随机插入一张内容图片
            try {
                File contentImageFile = imageUrl;
                BufferedImage contentImage = ImageIO.read(contentImageFile);

                // 定义目标宽度和高度
                int targetWidth = 475;
                int targetHeight = 632;
                int cornerRadius = 20; // 圆角半径

                // 计算保持比例的缩放尺寸，使图片至少有一个维度达到目标大小
                int originalWidth = contentImage.getWidth();
                int originalHeight = contentImage.getHeight();
                double widthRatio = (double) targetWidth / originalWidth;
                double heightRatio = (double) targetHeight / originalHeight;
                double ratio = Math.max(widthRatio, heightRatio); // 取较大比例以铺满

                int scaledWidth = (int) (originalWidth * ratio);
                int scaledHeight = (int) (originalHeight * ratio);

                // 创建带圆角的 BufferedImage
                BufferedImage roundedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
                Graphics2D imgG2d = roundedImage.createGraphics();
                imgG2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 计算绘制位置，居中裁剪
                int xOffset = (scaledWidth - targetWidth) / 2;
                int yOffset = (scaledHeight - targetHeight) / 2;

                // 绘制圆角矩形作为裁剪区域
                imgG2d.setClip(new java.awt.geom.RoundRectangle2D.Float(0, 0, targetWidth, targetHeight, cornerRadius, cornerRadius));
                imgG2d.drawImage(contentImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH), -xOffset, -yOffset, null);
                imgG2d.dispose();

                // 绘制带圆角的图片，左边与昵称左边对齐
                g2d.drawImage(roundedImage, x + 140, contentEndY, null);
                contentEndY += targetHeight + 40; // 20 为图片和时间地点之间的间距
            } catch (IOException e) {
                System.err.println("加载内容图片失败: " + e.getMessage());
            }
        contentEndY = contentEndY + 40;
        // 绘制时间和地点信息，左边与昵称左边对齐
        g2d.setColor(new Color(153, 153, 153));
        // 字体替换为黑体
        g2d.setFont(new Font("黑体", Font.PLAIN, 45));
        String timeText = time + "·" + location;
        g2d.drawString(timeText, x + 140, contentEndY);

        // 计算地点文字的宽度
        int locationTextWidth = g2d.getFontMetrics().stringWidth(timeText);
        // 在地点右边 30px 处添加蓝色的“回复”文字
        g2d.setColor(Color.decode("#666666"));
        g2d.setFont(new Font("黑体", Font.BOLD, 45));
        g2d.drawString("回复", x + 200 + locationTextWidth , contentEndY);

        // 计算“回复”文字的宽度
        int replyTextWidth = g2d.getFontMetrics().stringWidth("回复");
        g2d.setFont(new Font("Roboto Mono", Font.PLAIN, 45));
        // 定义横向区域相关参数
        String likeText = count>1000?String.format("%.1fw", count / 10000.0):count+"";
        int likeImageWidth = 45;
        int noLikeImageWidth = 45;
        int textWidth = g2d.getFontMetrics().stringWidth(likeText);
        int spacing = 50;

        // 计算横向区域的起始 x 坐标，放置在最右边
        int rightX = maxWidth + x - likeImageWidth - textWidth - spacing - noLikeImageWidth+60;

        // 绘制 like 图片
        if (likeImage != null) {
            g2d.drawImage(likeImage, rightX, contentEndY - 45, null);
        }
        // 绘制 like 文字
        g2d.setColor(Color.decode("#666666"));
        g2d.drawString(likeText, rightX + likeImageWidth + 20, contentEndY);

        // 绘制 no_like 图片
        if (noLikeImage != null) {
            g2d.drawImage(noLikeImage, rightX + likeImageWidth + textWidth + spacing, contentEndY - 45, null);
        }
        return contentEndY;
    }

    private static void drawComments(Graphics2D g2d, int x, int y, int width, int height,
                                     List<Comment> comments) {
        // 增大评论高度
        int commentHeight = 160;
        Color commentBgColor = new Color(0xffffff);

        // 让评论区起始 x 坐标和内容图片左边对齐
        int commentStartX = x + 140;

        for (int i = 0; i < comments.size(); i++) {
            Comment c = comments.get(i);
            g2d.setColor(commentBgColor);
            // 调整评论背景框的位置
            g2d.fillRoundRect(commentStartX, y + i * commentHeight, width - 200, commentHeight, 20, 20);
            drawComment(g2d, commentStartX, y + i * commentHeight + 20, c, width - 100, commentStartX);
        }
    }

    private static void drawComment(Graphics2D g2d, int x, int y, Comment c, int maxWidth, int contentImageLeftX) {
        // 调用 drawAvatar 方法，传入评论区头像尺寸 40
        drawAvatar(g2d, x, y, 80);

        g2d.setColor(Color.decode("#808080"));
        g2d.setFont(new Font("黑体", Font.PLAIN, 40));
        // 调整昵称的 x 坐标，适配新的头像位置
        g2d.drawString(RedBookStyleNicknameGenerator.generateRedBookNickname(), x + 100, y + 30);

        g2d.setColor(Color.decode("#333333"));
        g2d.setFont(new Font("黑体", Font.PLAIN, 45));
        List<String> lines = wrapText(g2d, c.content, maxWidth - 100);
        int lineHeight = g2d.getFontMetrics().getHeight();
        int commentContentEndY = y + 50;

        for (int i = 0; i < lines.size(); i++) {
            // 调整评论内容的 x 坐标，适配新的头像位置
            g2d.drawString(lines.get(i), x + 100, commentContentEndY + (i + 1) * lineHeight);
        }
        commentContentEndY += lines.size() * lineHeight + 10;

        // 模拟评论的时间、地点、点赞数和不点赞数
        String commentTime = c.time;
        String commentLocation = RandomProvinceGenerator.getRandomProvince();
        int noLikeCount = 50;
        commentContentEndY +=70;
        // 绘制评论的时间和地点，左边对齐内容图片
        g2d.setColor(Color.decode("#808080"));
        g2d.setFont(new Font("黑体", Font.PLAIN, 45));
        String timeText = commentTime + "·" + commentLocation;
        g2d.drawString(timeText, x + 100, commentContentEndY);

        // 计算地点文字的宽度
        int locationTextWidth = g2d.getFontMetrics().stringWidth(timeText);
        // 在地点右边 30px 处添加蓝色的“回复”文字
        g2d.setFont(new Font("黑体", Font.BOLD, 45));
        g2d.setColor(Color.decode("#666666"));
        g2d.drawString("回复", x+140+locationTextWidth+20, commentContentEndY);

        // 计算“回复”文字的宽度
        int replyTextWidth = g2d.getFontMetrics().stringWidth("回复");

        g2d.setFont(new Font("Roboto Mono", Font.PLAIN, 45));
        // 定义横向区域相关参数
        String likeText =c.like>1000? String.format("%.1fw", c.like / 10000.0):c.like+"";
        String noLikeText = String.format("%.1fw", noLikeCount / 10000.0);
        int likeImageWidth = 45;
        int noLikeImageWidth = 45;
        int likeTextWidth = g2d.getFontMetrics().stringWidth(likeText);
        int noLikeTextWidth = g2d.getFontMetrics().stringWidth(noLikeText);
        int spacing = 50;
        int rightX = 0;
        // 计算横向区域的起始 x 坐标，放置在最右边
        if(c.like>100000){
            rightX = x+60+locationTextWidth+replyTextWidth+171;
        }else if(c.like<999){
            rightX = x+60+locationTextWidth+replyTextWidth+220;
        }else{
            rightX = x+60+locationTextWidth+replyTextWidth+196;
        }


        // 绘制 like 图片
        if (likeImage != null) {
            g2d.drawImage(likeImage, rightX, commentContentEndY - 45, null);
        }
        // 绘制 like 文字
        g2d.setColor(Color.decode("#666666"));
        g2d.drawString(likeText, rightX + likeImageWidth + 20, commentContentEndY);

        // 绘制 no_like 图片
        if (noLikeImage != null) {
            g2d.drawImage(noLikeImage, rightX + likeImageWidth + likeTextWidth + spacing,
                    commentContentEndY - 45, null);
        }
        // 绘制 no_like 文字
//        g2d.drawString(noLikeText, rightX + likeImageWidth + likeTextWidth + spacing + noLikeImageWidth + 5, commentContentEndY);
    }

    // ... 已有代码 ...



    // 修改 drawAvatar 方法，接收头像尺寸参数
    private static void drawAvatar(Graphics2D g2d, int x, int y, int diameter) {
        if (!avatarFiles.isEmpty()) {
            try {
                File avatarFile = avatarFiles.get(random.nextInt(avatarFiles.size()));
                System.out.println("当前选择的头像文件: " + avatarFile.getAbsolutePath());
                BufferedImage avatarImg = ImageIO.read(avatarFile);

                BufferedImage circularAvatar = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);
                Graphics2D ag = circularAvatar.createGraphics();
                ag.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                ag.setClip(new Ellipse2D.Float(0, 0, diameter, diameter));
                ag.drawImage(avatarImg.getScaledInstance(diameter, diameter, Image.SCALE_SMOOTH), 0, 0, null);
                ag.dispose();

                g2d.drawImage(circularAvatar, x, y, null);
            } catch (IOException e) {
                System.err.println("加载头像图片失败: " + e.getMessage());
                g2d.setColor(Color.LIGHT_GRAY);
                g2d.fillOval(x, y, diameter, diameter);
            }
        } else {
            g2d.setColor(Color.LIGHT_GRAY);
            g2d.fillOval(x, y, diameter, diameter);
        }
    }

    private static List<String> wrapText(Graphics2D g2d, String text, int maxWidth) {
        List<String> lines = new ArrayList<>();
        //每16个字符为一行
        for (int i = 0; i < text.length(); i++) {
            if (i % 17 == 0) {
                lines.add(text.substring(i, Math.min(i + 17, text.length())));
            }
        }
        return lines;
    }
    private static List<String> wrapContentText(Graphics2D g2d, String text, int maxWidth) {
        List<String> lines = new ArrayList<>();
        //每16个字符为一行
        for (int i = 0; i < text.length(); i++) {
            if (i % 20 == 0) {
                lines.add(text.substring(i, Math.min(i + 20, text.length())));
            }
        }
        return lines;
    }

}